<!--
 * @Author: 瞿旺兴 18774621495@163.com
 * @Date: 2022-05-18 14:23:47
 * @LastEditors: 瞿旺兴 18774621495@163.com
 * @LastEditTime: 2022-06-08 17:24:43
 * @FilePath: \nien-vue3-admin\src\views\finance\FinancialManagementTools\accountMaintain\index.vue
 * @Description: 用户导入弹窗
-->
<template>
  <el-dialog v-model="visible" title="用户导入">
    <el-upload
      ref="uploadRef"
      drag
      action="#"
      :on-remove="handleRemove"
      :http-request="handleSuccess"
      multiple
      :limit="1"
      accept=".xls,.xlsx"
      :on-exceed="handleExceed"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将文件拖入此处<em>点击上传</em>
      </div>
    </el-upload>
    <div>
      <el-link type="primary" @click="downLoadTemp">下载模板</el-link>
      <p class="danger">提示:仅允许导入"xls"或"xlsx"格式文件!</p>
    </div>
    <template #footer>
      <div>
        <el-button type="primary" :loading="loading" @click="confirm">确定</el-button>
        <el-button type="info" @click="cancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineEmits, defineExpose, getCurrentInstance } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { importInfo } from '@/api/finance/FinancialManagementTools'

const uploadRef = ref(null)
const visible = ref<boolean>(false)
const loading = ref<boolean>(false)
const fileName = 'file'
const emits = defineEmits(['success'])
const {
  appContext: {
    config: {
      globalProperties: { $download },
    },
  },
} = getCurrentInstance()

const fileData = new FormData()

const downLoadTemp = () => {
  $download('/finance/collectionTicketingInfo/downloadImportTemplate', {}, '开票信息模板.xlsx')
}

const confirm = () => {
  loading.value = true
  importInfo(fileData).then(res => {
    if (res.code === 200) {
      ElMessage.success('导入成功！')
      emits('success')
      cancel()
    }
  }).finally(() => {
    loading.value = false
  })
}
const cancel = () => {
  uploadRef.value.clearFiles()
  fileData.delete(fileName)
  visible.value = false
}

const handleSuccess = ({ file }) => {
  fileData.append(fileName, file)
  return Promise.resolve()
}
const handleRemove = () => {
  fileData.delete(fileName)
}
const handleExceed = () => {
  ElMessage.warning('最多上传一个文件！')
}
defineExpose({
  visible,
})
</script>

<style lang="less" scoped>
.danger{
  color: var(--el-color-danger)
}

</style>